<template>
  <div class="w-full">
    <div class="flex flex-a-c">
      <a-tooltip v-if="inputValue" :content="inputValue" position="top" mini>
        <div style="max-width: 300px; width: fit-content" class="mr-10 text-overflow-1 text-theme">
          {{ inputValue }}
        </div>
      </a-tooltip>
      <template v-if="inputValue">
        <a-button type="primary" @click="handleClickChoose" :loading="displayLoading" size="mini">
          <template #icon>
            <icon-attachment />
          </template>
          <template #default>重新选择</template>
        </a-button>
        <a-button class="ml-10" type="primary" status="danger" @click="handleInputChange('')" size="mini">
          <template #icon>
            <icon-delete />
          </template>
          <template #default>删除</template>
        </a-button>
      </template>
      <template v-else="inputValue">
        <a-button type="primary" @click="handleClickChoose" :loading="displayLoading" size="mini">
          <template #icon>
            <icon-attachment />
          </template>
          <template #default>点击选择</template>
        </a-button>
      </template>
    </div>
    <a-modal
      v-model:visible="visible"
      width="80%"
      :footer="false"
      draggable
      unmount-on-close
      :bodyStyle="{ padding: '16px 0' }"
    >
      <template #title>
        <span class="font-bold">功能选择</span>
      </template>
      <div class="flex-col" :style="{ height: modalHeight, overflowY: 'auto' }">
        <template v-if="tabList.length > 1">
          <a-radio-group v-model="tabCurrent" class="px-20 box-border">
            <template v-for="item in tabList" :key="item.id" :value="item.id">
              <a-radio class="mb-10">
                <template #radio="{ checked }">
                  <a-button
                    :type="tabCurrent === item.id ? 'primary' : 'secondary'"
                    size="small"
                    @click="handleChangeTab(item)"
                    >{{ item.name }}</a-button
                  >
                </template>
              </a-radio>
            </template>
          </a-radio-group>
          <a-divider :margin="10" />
        </template>
        <section class="w-full flex-1 overflow-hidden">
          <transition name="fade-slide" mode="out-in" appear>
            <keep-alive>
              <component
                :is="menuList[selectedKeyIndex].name"
                :tabCurrentInfo="tabCurrentInfo"
                :displayInfo="displayInfo"
                @handleCheck="handleCheck"
              ></component>
            </keep-alive>
          </transition>
        </section>
      </div>
    </a-modal>
  </div>
</template>

<script setup>
/*
使用示例
<MsPopup v-model="form.link"></MsPopup>
*/
import { linkTypeList, linkDisplay } from '@/apis'
import App from './app.vue'
import ArticleLibrary from './articleLibrary.vue'
import GoodsLibrary from './goodsLibrary.vue'
import MarketingActivity from './marketingActivity.vue'
import Shop from './shop.vue'
import GoodsDetail from './goodsDetail.vue'
import GoodsMaterial from './goodsMaterial.vue'
import FreeBuy from './freeBuy.vue'
import AllianceActivities from './allianceActivities.vue'
import CustomLink from './customLink.vue'
import LifeCard from './lifeCard.vue'
import CustomerService from './customerService.vue'
import BusinessSchool from './businessSchool.vue'
import BusinessSchoolCate from './businessSchoolCate.vue'
import LocalLife from './localLife.vue'
import { reAssign } from '@/utils/common'

defineOptions({ name: 'MsPopup' })

const emit = defineEmits(['update:modelValue', 'change'])
const props = defineProps({
  modelValue: {
    default: undefined,
    type: [String, undefined]
  },
  limit: {
    default: [],
    type: [Array, undefined]
  }
})
const selectedKeyIndex = ref(0)
const menuList = shallowRef([
  {
    id: 1,
    name: App //APP页面
  },
  {
    id: 2,
    name: ArticleLibrary //文章库
  },
  {
    id: 3,
    name: GoodsLibrary //商品库
  },
  {
    id: 4,
    name: FreeBuy //零元购
  },
  {
    id: 5,
    name: GoodsDetail //商品详情
  },
  {
    id: 6,
    name: GoodsMaterial //商品素材页面
  },
  {
    id: 7,
    name: AllianceActivities //联盟活动
  },
  {
    id: 8,
    name: MarketingActivity //营销活动
  },
  // {
  //   id: 9,
  //   name: CustomLink //自定义外链
  // },
  {
    id: 10,
    name: LifeCard //生活特权卡商品
  },
  {
    id: 11,
    name: CustomerService //企微客服
  },
  {
    id: 13,
    name: BusinessSchool //商学院
  },
  {
    id: 14,
    name: Shop //店铺页面
  },
  {
    id: 15,
    name: AllianceActivities //官方活动
  },
  {
    id: 16,
    name: AllianceActivities //自定义联盟活动
  },
  {
    id: 20,
    name: App //H5页面
  },
  {
    id: 21,
    name: App //自定义交互
  },
  {
    id: 22,
    name: LocalLife //本地生活
  },
  {
    id: 23,
    name: BusinessSchoolCate //商学院分类
  },
  {
    id: 24,
    name: MarketingActivity //营销活动
  }
])
const visible = ref(false)
const inputValue = ref()
const modalHeight = ref('0px')
const tabList = ref([])
const tabCurrent = ref(0)
const tabCurrentInfo = ref()
const displayLoading = ref(false)
const displayInfo = reactive({
  typeId: undefined,
  id: undefined,
  link: undefined,
  currentId: undefined
})
const handleInputChange = (e) => {
  emit('update:modelValue', e)
  emit('change', e)
}
watch(
  () => props.limit,
  (e) => {
    if (e.length) {
      menuList.value = menuList.value.filter((item) => e.includes(item.id))
    }
  },
  { immediate: true }
)
watch(
  () => props.modelValue,
  async (newValue) => {
    if (!newValue) inputValue.value = ''
    else {
      const res = await linkDisplay({ rule: newValue })
      inputValue.value = `${res.data.typeTitle ? '【' + res.data.typeTitle + '】' : ''} ${res.data.title}`
      reAssign(displayInfo, res?.data ?? false)
      displayInfo.link = newValue
    }
  }
)

const updateModalHeight = () => {
  const windowHeight = window.innerHeight
  modalHeight.value = `${windowHeight * 0.7 - 50}px`
}
onMounted(async () => {
  if (!props.modelValue) inputValue.value = ''
  else {
    const res = await linkDisplay({ rule: props.modelValue })
    inputValue.value = `${res.data.typeTitle ? '【' + res.data.typeTitle + '】' : ''} ${res.data.title}`
    reAssign(displayInfo, res?.data ?? false)
    displayInfo.link = props.modelValue
  }

  updateModalHeight() // 初始加载时设置弹窗高度
  window.addEventListener('resize', updateModalHeight) // 监听窗口大小变化
})

onUnmounted(() => {
  window.removeEventListener('resize', updateModalHeight) // 移除事件监听器
})

const handleChangeTab = (item) => {
  if (tabCurrent.value != item.id) {
    tabCurrent.value = item.id
    tabCurrentInfo.value = item
    selectedKeyIndex.value = menuList.value.findIndex((item) => item.id == tabCurrent.value)
    displayInfo.currentId = tabCurrent.value
  }
}

const handleCheck = (res) => {
  if (res) handleInputChange(res)
  visible.value = false
}

const handleClickChoose = async () => {
  try {
    displayLoading.value = true
    const res = await linkTypeList()
    const res2 = res?.data ?? []
    if (props.limit.length) tabList.value = res2.filter((item) => props.limit.includes(item.id))
    else tabList.value = res2
    tabCurrentInfo.value = tabList.value[0]
    tabCurrent.value = tabCurrentInfo.value.id
    if (displayInfo.typeId) {
      const index = tabList.value.findIndex((item) => item.id == displayInfo.typeId)
      if (index != -1) {
        tabCurrentInfo.value = tabList.value[index]
        tabCurrent.value = tabCurrentInfo.value.id
      }
    }
    selectedKeyIndex.value = menuList.value.findIndex((item) => item.id == tabCurrent.value)
    displayInfo.currentId = tabCurrent.value
    visible.value = true
  } finally {
    displayLoading.value = false
  }
}
</script>

<style scoped lang="scss">
.arco-radio-group .arco-radio {
  margin-right: 10px;
}
</style>
